from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from app import db
from app.models import User, Activity, Course, Organization
from app.forms import UserForm, AdminActivityForm, AdminCourseForm, AdminOrganizationForm
from app.utils import admin_required

admin_bp = Blueprint('admin', __name__)

@admin_bp.route('/dashboard')
@login_required
@admin_required
def dashboard():
    users_count = User.query.count()
    activities_count = Activity.query.count()
    courses_count = Course.query.count()
    orgs_count = Organization.query.count()
    
    recent_users = User.query.order_by(User.created_at.desc()).limit(5).all()
    recent_activities = Activity.query.order_by(Activity.created_at.desc()).limit(5).all()
    
    return render_template('admin/dashboard.html', 
                         users_count=users_count,
                         activities_count=activities_count,
                         courses_count=courses_count,
                         orgs_count=orgs_count,
                         recent_users=recent_users,
                         recent_activities=recent_activities)

@admin_bp.route('/users')
@login_required
@admin_required
def manage_users():
    page = request.args.get('page', 1, type=int)
    users = User.query.order_by(User.created_at.desc()).paginate(
        page=page, per_page=current_app.config['ITEMS_PER_PAGE'], error_out=False)
    return render_template('admin/users.html', users=users)

@admin_bp.route('/user/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_user(id):
    user = User.query.get_or_404(id)
    form = UserForm(obj=user)
    
    if form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        user.role = form.role.data
        user.active = form.active.data
        
        if form.password.data:
            user.set_password(form.password.data)
        
        db.session.commit()
        flash('用户信息已更新', 'success')
        return redirect(url_for('admin.manage_users'))
    
    return render_template('admin/user_form.html', form=form, user=user)

@admin_bp.route('/user/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    if user == current_user:
        flash('不能删除当前登录的用户', 'danger')
        return redirect(url_for('admin.manage_users'))
    
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除', 'success')
    return redirect(url_for('admin.manage_users'))

# 类似的管理活动和课程的路由...